import { Plugin } from './Plugin';
import { Validator, ValidatorType } from '../validators/Validator';

export type ParamsValidation<T> = {
  request: {
    params: {
      [key in keyof T]: ValidatorType<T[key]>;
    };
  };
};

export class PluginParam extends Plugin<Plugin.Web, ParamsValidation<any>> {
  constructor(data: Record<string, Validator>) {
    super();
    const parsedData = Object.entries(data);

    this.use((ctx, next) => {
      const rawParams = this.getParams(ctx);
      const params: typeof ctx.request.params = ctx.request.params = {};

      for (const [key, validator] of parsedData) {
        params[key] = rawParams[key];

        const msg = validator.validate(ctx.app.i18n, params, key);
        if (msg) {
          ctx.throw(400, msg);
        }
      }

      return next();
    });
  }
}
